package com.jdyfy.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.jdyfy.entity.User;
import com.jdyfy.exception.ServiceException;
import com.jdyfy.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import static com.jdyfy.constant.MessageConstant.*;

@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        //1、从请求头中获取令牌
        String token = request.getHeader("token");

        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        // 执行认证
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(TOKEN_NOT_EXIST);
        }

        // 获取 token 中的username
        String username;
        User user;
        try {
            username = JWT.decode(token).getAudience().get(0);
            // 根据token中的userid查询数据库
            user = userService.getByUsername(username);
        } catch (Exception e) {
            throw new ServiceException(TOKEN_INVALID);
        }

        if (user == null) {
            throw new ServiceException(ACCOUNT_NOT_FOUND);
        }
        try {
            // 用户密码加签验证 token
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e) {
            throw new ServiceException(TOKEN_INVALID);
        }
        return true;

        //return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}